package com.videoweb.service.impl;//package com.video.service.impl;
//

import com.videoweb.constant.Constants;
import com.videoweb.exception.ServiceException;
import com.videoweb.model.LoginUser;
import com.videoweb.entity.User;
import com.videoweb.service.IUserService;
import com.videoweb.utils.MessageUtils;
import com.videoweb.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * 用户验证处理
 *
 * @author lmr
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService
{
//    日志：
    private static final Logger log = LoggerFactory.getLogger(UserDetailsServiceImpl.class);

    @Autowired
    private IUserService userService;

    @Autowired
    private  PermissionService permissionService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException
    {
//       在这里通过连接数据库来查找用户
        User user = userService.findUserByUserName(username);
//TODO 对登录信息进行校验

        if (StringUtils.isNull(user))
        {
            log.info("登录用户：{} 不存在.", username);
            throw new ServiceException(MessageUtils.message("user.not.exists"));
        }
// 验证密码
        userService.validate(user);
//      createLoginUser方法就在下面
        return createLoginUser(user);
    }

    public UserDetails createLoginUser(User user)
    {
//        转一下
        user.setAvatar(Constants.CNAME +user.getAvatar());

//        本质还是UserDetails哈
        return new LoginUser(user.getId(), user, permissionService.getMenuPermission(user));
    }
}
